package com.androidbook.garbagedemo1.api;

import android.util.Log;

import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class Api {
    private static OkHttpClient client;
    private static String requestUrl;
    private static HashMap<String,Object> mParams;
    public static com.androidbook.garbagedemo1.api.Api api = new com.androidbook.garbagedemo1.api.Api( );
    public Api( ) {
    }
    public static com.androidbook.garbagedemo1.api.Api config(String url, HashMap<String,Object> params){
        client = new OkHttpClient. Builder()
                .build();
        requestUrl = ApiConfig.BASE_URL+url;
        mParams = params;
        return api;
    }

    public void postRequest(TtitCallback callback){

        JSONObject jsonObject = new JSONObject(mParams) ;
        String jsonStr = jsonObject.toString();//转成json字符串
        RequestBody requestBodyJson =
                RequestBody.create (MediaType.parse( "application/json;charset=utf-8")
                        ,jsonStr);//设置请求体
        //第二步创建Rquest
        Request request=new Request.Builder()
                .url(requestUrl)//请求地址
                .addHeader("contentType","application/json);charset=UTF-8")//请求头
                .post(requestBodyJson)//请求方法
                .build();
        //第三步创建call回调对象
        final Call call=client.newCall(request);
        //第四步发起请求
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("onFailure",e.getMessage());//失败
                callback.onFailure(e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String result=response.body().string();//成功
                callback.onSuccess(result);

            }
        });
    }

}
